package com.wanban.player

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

import com.wanban.screencast.ScreenCastUtils
import com.wanban.screencast.listener.OnDeviceConnectListener
import com.wanban.screencast.listener.OnSearchedDevicesListener
import com.wanban.screencast.listener.OnVideoProgressUpdateListener
import com.wanban.screencast.model.DeviceModel


class VideoCasScreenDialog(context: Context, style: Int = R.style.Down2UpDialogStyle) : Dialog(context, style), OnSearchedDevicesListener,
    OnVideoProgressUpdateListener {

    // 返回按钮
    private lateinit var btnBack: View
    // 竖屏时顶部触摸区域
    private lateinit var topLayout: View
    // 投屏UI区域
    private lateinit var layoutCastScreen: ViewGroup
    // 当搜索不到设备时，显示搜索状态
    private lateinit var layoutCastScreenEmpty: ViewGroup
    // 设备列表
    private lateinit var deviceRecyclerView: RecyclerView
    // 当搜索不到设备时，提示用户如何连接
    private lateinit var layoutMethod: ViewGroup

    // 视频url
    private var videoUrl: String? = null
    // 视频名称
    private var title: String? = null

    // 起播位置
    private var startPosition: Long = 0L

    // 当前视频是否全屏
    private var isFullScreen = false

    // 投屏视频是否正在播放
    private var isCastScreenVideoPlaying = false

    // 是否停止更新当前投屏视频进度
    private var isStopUpdateCurrentPosition = false

    // 投屏回调
    private var onCastScreenCallback: OnCastScreenCallback? = null
    // 当前正在连接的设备
    private var connectedDevice: DeviceModel? = null
    private val adapter by lazy { CastScreenDevicesAdapter(ArrayList()) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 设置当前dialog的位置
        setDialogWindow()
        setContentView(R.layout.dialog_video_cast_screen)
        // 设置弹窗可返回或触摸取消
        setCancelable(true)
        setCanceledOnTouchOutside(true)

        btnBack = findViewById(R.id.btn_close_cast_screen)
        topLayout = findViewById(R.id.video_cast_screen_tip)
        layoutCastScreen = findViewById(R.id.layout_cast_screen)
        layoutCastScreenEmpty = findViewById(R.id.layout_empty_devices)
        deviceRecyclerView = findViewById(R.id.cast_screen_recycler)
        layoutMethod = findViewById(R.id.layout_cast_screen_method)

        deviceRecyclerView.layoutManager = LinearLayoutManager(context)
        deviceRecyclerView.adapter = adapter

        adapter.setOnItemClickListener { _, _, position ->
            connectedDevice = adapter.getItem(position)
            if (TextUtils.isEmpty(connectedDevice?.name)) return@setOnItemClickListener
            onCastScreenCallback?.onReadyToConnect(connectedDevice?.name!!)

            ScreenCastUtils.connectDevice(connectedDevice?.name!!, object : OnDeviceConnectListener {
                override fun onDeviceConnect() {
                    onCastScreenCallback?.onConnect()
                    if (TextUtils.isEmpty(videoUrl)) {
                        onCastScreenCallback?.onDisconnect("视频播放地址Null！")
                        return
                    }
                    isCastScreenVideoPlaying = true
                    ScreenCastUtils.play(videoUrl!!, title, this@VideoCasScreenDialog)
                    onCastScreenCallback?.onStart()
                }

                override fun onDeviceDisConnect() {
                    onCastScreenCallback?.onDisconnect("链接失败，请重试！")
                }
            })
            dismiss()
        }

        btnBack.setOnClickListener {
            stopScreenCast()
            dismiss()
        }
        topLayout.setOnClickListener {
            stopScreenCast()
            dismiss()
        }

        // 设置顶部空白布局的状态
        topLayout.visibility = if (isFullScreen) {
            View.GONE
        } else {
            View.VISIBLE
        }
    }


    fun show(videoUrl: String, title: String?, startPosition: Long, duration: Int) {
        super.show()
        this.title = title
        this.videoUrl = videoUrl
        this.startPosition = startPosition
        // 开始扫描设备， 显示加载状态
        layoutCastScreenEmpty.visibility = View.VISIBLE
        adapter.setList(ArrayList())
        ScreenCastUtils.setDuration(duration)
        ScreenCastUtils.startBrowser(this)

    }


    // 当前投屏视频是否正在播放
    private fun isPlaying(): Boolean {
        if (connectedDevice == null) return false
        return isCastScreenVideoPlaying
    }

    /**
     * 开始或暂停投屏视频
     * @return 返回切换后的当前状态
     */
    fun startOrPauseCastScreen(): Boolean {
        if (connectedDevice == null) return false
        if (isCastScreenVideoPlaying) {
            ScreenCastUtils.pause()
            onCastScreenCallback?.onPause()
        } else {
            ScreenCastUtils.play(videoUrl!!, title, this@VideoCasScreenDialog)
            onCastScreenCallback?.onStart()
        }
        isCastScreenVideoPlaying = !isCastScreenVideoPlaying
        return isCastScreenVideoPlaying
    }

    fun start(){
        if (connectedDevice == null) return
        ScreenCastUtils.play(videoUrl!!, title, this@VideoCasScreenDialog)
    }

    fun pause(){
        if (connectedDevice == null) return
        ScreenCastUtils.pause()
    }

    /**
     * 投屏视频seek
     */
    fun castScreenSeekTo(seekTo: Int) {
        if (connectedDevice == null) return
        // 单位是秒
        ScreenCastUtils.seekTo(seekTo)
    }

    /**
     * 投屏设备断开连接
     */
    fun disconnect() {
        connectedDevice = null
        isCastScreenVideoPlaying = false
        ScreenCastUtils.stop()
        ScreenCastUtils.stopBrowser()
    }

    fun isStopUpdateCurrentPosition(isStopUpdate: Boolean) {
        isStopUpdateCurrentPosition = isStopUpdate
    }

    fun setFullScreenStatus(isFullScreen: Boolean) {
        this.isFullScreen = isFullScreen
    }

    fun setCastScreenCallback(listener: OnCastScreenCallback) {
        onCastScreenCallback = listener
    }

    // 用户取消了投屏，比如点击返回
    private fun stopScreenCast(){
        ScreenCastUtils.stopBrowser()
        ScreenCastUtils.stop()
    }

    private fun setDialogWindow() {
        window?.decorView?.setPadding(0, 0, 0, 0)
        val params = window?.attributes
        params?.width = ViewGroup.LayoutParams.MATCH_PARENT
        params?.height = ViewGroup.LayoutParams.MATCH_PARENT
        params?.gravity = Gravity.BOTTOM
        window?.attributes = params
    }

    override fun onSearchedDevices(devices: List<DeviceModel>) {
        Log.e("ScreenCast", "onSearchedDevices..." + devices.size)
        if (devices.isEmpty()) {
            layoutCastScreenEmpty.visibility = View.VISIBLE
            layoutMethod.visibility = View.VISIBLE
        } else {
            layoutCastScreenEmpty.visibility = View.GONE
            layoutMethod.visibility = View.GONE
        }
        adapter.setList(devices)
    }

    override fun onVideoProgressUpdate(time: Long) {
        onCastScreenCallback?.onPositionUpdate(time)
    }


}